<template>
  <div class="container mx-auto px-4 py-8">
    <h1 class="text-2xl font-bold mb-6">用户管理</h1>
    
    <div v-if="loading" class="flex justify-center py-8">
      <div class="animate-spin rounded-full h-12 w-12 border-t-2 border-b-2 border-primary"></div>
    </div>
    
    <div v-else>
      <!-- 搜索和过滤 -->
      <div class="bg-white rounded-lg shadow-sm p-4 mb-6">
        <div class="flex flex-col md:flex-row md:items-center space-y-4 md:space-y-0 md:space-x-4">
          <div class="flex-1">
            <div class="relative">
              <input 
                v-model="searchQuery" 
                type="text" 
                placeholder="搜索用户名、邮箱或手机号" 
                class="w-full pl-10 pr-4 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent"
                @keyup.enter="searchUsers"
              />
              <div class="absolute left-3 top-1/2 transform -translate-y-1/2">
                <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5 text-gray-400" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z" />
                </svg>
              </div>
            </div>
          </div>
          
          <div class="flex space-x-4">
            <select 
              v-model="roleFilter" 
              class="px-4 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent"
              @change="fetchUsers(1)"
            >
              <option value="">所有角色</option>
              <option value="ROLE_USER">普通用户</option>
              <option value="ROLE_ADMIN">管理员</option>
            </select>
            
            <select 
              v-model="statusFilter" 
              class="px-4 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent"
              @change="fetchUsers(1)"
            >
              <option value="">所有状态</option>
              <option value="1">正常</option>
              <option value="0">禁用</option>
            </select>
            
            <button 
              @click="searchUsers"
              class="px-4 py-2 bg-primary text-white rounded-md hover:bg-primary-dark transition"
            >
              搜索
            </button>
          </div>
        </div>
      </div>
      
      <!-- 用户列表 -->
      <div class="bg-white rounded-lg shadow-sm overflow-hidden mb-6">
        <div class="overflow-x-auto">
          <table class="min-w-full divide-y divide-gray-200">
            <thead class="bg-gray-50">
              <tr>
                <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                  用户信息
                </th>
                <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                  角色
                </th>
                <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                  注册时间
                </th>
                <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                  状态
                </th>
                <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                  操作
                </th>
              </tr>
            </thead>
            <tbody class="bg-white divide-y divide-gray-200">
              <tr v-if="users.length === 0">
                <td colspan="5" class="px-6 py-4 text-center text-gray-500">
                  暂无用户数据
                </td>
              </tr>
              <tr v-for="user in users" :key="user.id" class="hover:bg-gray-50">
                <td class="px-6 py-4 whitespace-nowrap">
                  <div class="flex items-center">
                    <div class="flex-shrink-0 h-10 w-10">
                      <img 
                        :src="user.avatar || '/default-avatar.png'" 
                        class="h-10 w-10 rounded-full object-cover"
                        alt="用户头像"
                      />
                    </div>
                    <div class="ml-4">
                      <div class="text-sm font-medium text-gray-900">{{ user.username }}</div>
                      <div class="text-sm text-gray-500">{{ user.email || '未设置邮箱' }}</div>
                      <div class="text-sm text-gray-500">{{ user.phone || '未设置手机' }}</div>
                    </div>
                  </div>
                </td>
                <td class="px-6 py-4 whitespace-nowrap">
                  <div v-for="role in user.roles" :key="role.id" 
                    class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium mr-2"
                    :class="role.name === 'ROLE_ADMIN' ? 'bg-purple-100 text-purple-800' : 'bg-blue-100 text-blue-800'"
                  >
                    {{ getRoleName(role.name) }}
                  </div>
                </td>
                <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                  {{ formatDateTime(user.createTime) }}
                </td>
                <td class="px-6 py-4 whitespace-nowrap">
                  <span 
                    class="px-2 inline-flex text-xs leading-5 font-semibold rounded-full"
                    :class="user.enabled ? 'bg-green-100 text-green-800' : 'bg-red-100 text-red-800'"
                  >
                    {{ user.enabled ? '正常' : '禁用' }}
                  </span>
                </td>
                <td class="px-6 py-4 whitespace-nowrap text-sm font-medium">
                  <button 
                    @click="editUser(user)"
                    class="text-indigo-600 hover:text-indigo-900 mr-3"
                  >
                    编辑
                  </button>
                  <button 
                    v-if="user.enabled"
                    @click="toggleUserStatus(user.id, false)"
                    class="text-red-600 hover:text-red-900 mr-3"
                  >
                    禁用
                  </button>
                  <button 
                    v-else
                    @click="toggleUserStatus(user.id, true)"
                    class="text-green-600 hover:text-green-900 mr-3"
                  >
                    启用
                  </button>
                  <button 
                    @click="resetPassword(user.id)"
                    class="text-yellow-600 hover:text-yellow-900"
                  >
                    重置密码
                  </button>
                </td>
              </tr>
            </tbody>
          </table>
        </div>
      </div>
      
      <!-- 分页 -->
      <div class="flex justify-between items-center">
        <div class="text-sm text-gray-500">
          共 {{ totalItems }} 条记录，当前第 {{ currentPage }} / {{ totalPages }} 页
        </div>
        <div class="flex space-x-2">
          <button 
            @click="fetchUsers(1)"
            :disabled="currentPage === 1"
            :class="[
              'px-3 py-1 rounded border',
              currentPage === 1 
                ? 'bg-gray-100 text-gray-400 cursor-not-allowed' 
                : 'bg-white text-gray-700 hover:bg-gray-50'
            ]"
          >
            首页
          </button>
          <button 
            @click="fetchUsers(currentPage - 1)"
            :disabled="currentPage === 1"
            :class="[
              'px-3 py-1 rounded border',
              currentPage === 1 
                ? 'bg-gray-100 text-gray-400 cursor-not-allowed' 
                : 'bg-white text-gray-700 hover:bg-gray-50'
            ]"
          >
            上一页
          </button>
          <button 
            @click="fetchUsers(currentPage + 1)"
            :disabled="currentPage === totalPages"
            :class="[
              'px-3 py-1 rounded border',
              currentPage === totalPages 
                ? 'bg-gray-100 text-gray-400 cursor-not-allowed' 
                : 'bg-white text-gray-700 hover:bg-gray-50'
            ]"
          >
            下一页
          </button>
          <button 
            @click="fetchUsers(totalPages)"
            :disabled="currentPage === totalPages"
            :class="[
              'px-3 py-1 rounded border',
              currentPage === totalPages 
                ? 'bg-gray-100 text-gray-400 cursor-not-allowed' 
                : 'bg-white text-gray-700 hover:bg-gray-50'
            ]"
          >
            末页
          </button>
        </div>
      </div>
    </div>
    
    <!-- 编辑用户弹窗 -->
    <div v-if="showEditModal" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
      <div class="bg-white rounded-lg shadow-xl w-full max-w-md p-6">
        <div class="flex justify-between items-center mb-4">
          <h2 class="text-xl font-bold">编辑用户</h2>
          <button @click="showEditModal = false" class="text-gray-500 hover:text-gray-700">
            <svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6" fill="none" viewBox="0 0 24 24" stroke="currentColor">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12" />
            </svg>
          </button>
        </div>
        
        <div class="space-y-4">
          <div>
            <label class="block text-sm font-medium text-gray-700 mb-1">用户名</label>
            <input 
              v-model="editingUser.username" 
              type="text" 
              class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent"
              disabled
            />
          </div>
          
          <div>
            <label class="block text-sm font-medium text-gray-700 mb-1">邮箱</label>
            <input 
              v-model="editingUser.email" 
              type="email" 
              class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent"
            />
          </div>
          
          <div>
            <label class="block text-sm font-medium text-gray-700 mb-1">手机号</label>
            <input 
              v-model="editingUser.phone" 
              type="text" 
              class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent"
            />
          </div>
          
          <div>
            <label class="block text-sm font-medium text-gray-700 mb-1">角色</label>
            <div class="space-x-4">
              <label class="inline-flex items-center">
                <input 
                  type="checkbox" 
                  value="ROLE_USER" 
                  v-model="editingUser.roleNames"
                  class="h-4 w-4 text-primary focus:ring-primary border-gray-300 rounded"
                />
                <span class="ml-2 text-sm text-gray-700">普通用户</span>
              </label>
              <label class="inline-flex items-center">
                <input 
                  type="checkbox" 
                  value="ROLE_ADMIN" 
                  v-model="editingUser.roleNames"
                  class="h-4 w-4 text-primary focus:ring-primary border-gray-300 rounded"
                />
                <span class="ml-2 text-sm text-gray-700">管理员</span>
              </label>
            </div>
          </div>
          
          <div>
            <label class="block text-sm font-medium text-gray-700 mb-1">状态</label>
            <div class="space-x-4">
              <label class="inline-flex items-center">
                <input 
                  type="radio" 
                  :value="true" 
                  v-model="editingUser.enabled"
                  class="h-4 w-4 text-primary focus:ring-primary border-gray-300"
                />
                <span class="ml-2 text-sm text-gray-700">正常</span>
              </label>
              <label class="inline-flex items-center">
                <input 
                  type="radio" 
                  :value="false" 
                  v-model="editingUser.enabled"
                  class="h-4 w-4 text-primary focus:ring-primary border-gray-300"
                />
                <span class="ml-2 text-sm text-gray-700">禁用</span>
              </label>
            </div>
          </div>
        </div>
        
        <div class="mt-6 flex justify-end space-x-3">
          <button 
            @click="showEditModal = false"
            class="px-4 py-2 border border-gray-300 rounded-md text-gray-700 hover:bg-gray-50 transition"
          >
            取消
          </button>
          <button 
            @click="saveUser"
            class="px-4 py-2 bg-primary text-white rounded-md hover:bg-primary-dark transition"
            :disabled="isSaving"
          >
            <span v-if="isSaving">保存中...</span>
            <span v-else>保存</span>
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import axios from 'axios'
import { onMounted, reactive, ref } from 'vue'

export default {
  name: 'UserManageView',
  setup() {
    const loading = ref(true)
    const users = ref([])
    const currentPage = ref(1)
    const pageSize = ref(10)
    const totalItems = ref(0)
    const totalPages = ref(0)
    const searchQuery = ref('')
    const roleFilter = ref('')
    const statusFilter = ref('')
    
    const showEditModal = ref(false)
    const editingUser = reactive({
      id: null,
      username: '',
      email: '',
      phone: '',
      enabled: true,
      roleNames: []
    })
    const isSaving = ref(false)
    
    const fetchUsers = async (page) => {
      if (page) {
        currentPage.value = page
      }
      
      loading.value = true
      try {
        const params = {
          page: currentPage.value - 1,
          size: pageSize.value,
          query: searchQuery.value,
          role: roleFilter.value,
          status: statusFilter.value
        }
        
        const response = await axios.get('/api/admin/users', {
          params
        })
        if (response.data.code === 200) {
          users.value = response.data.data.content
          totalItems.value = response.data.data.totalElements
          totalPages.value = response.data.data.totalPages
        } else {
          console.error('获取用户列表失败:', response.data.message)
        }
      } catch (error) {
        console.error('获取用户列表出错:', error)
      } finally {
        loading.value = false
      }
    }
    
    const searchUsers = () => {
      fetchUsers(1)
    }
    
    const editUser = (user) => {
      editingUser.id = user.id
      editingUser.username = user.username
      editingUser.email = user.email
      editingUser.phone = user.phone
      editingUser.enabled = user.enabled
      editingUser.roleNames = user.roles.map(role => role.name)
      
      showEditModal.value = true
    }
    
    const saveUser = async () => {
      if (isSaving.value) return
      
      isSaving.value = true
      try {
        const response = await axios.put(`/api/admin/users/${editingUser.id}`, {
          email: editingUser.email,
          phone: editingUser.phone,
          enabled: editingUser.enabled,
          roleNames: editingUser.roleNames
        })
        
        if (response.data.code === 200) {
          showEditModal.value = false
          fetchUsers(currentPage.value)
        } else {
          alert(response.data.message || '保存失败，请稍后重试')
        }
      } catch (error) {
        console.error('保存用户信息出错:', error)
        alert('保存失败，请稍后重试')
      } finally {
        isSaving.value = false
      }
    }
    
    const toggleUserStatus = async (userId, enabled) => {
      try {
        const response = await axios.put(`/api/admin/users/${userId}/status`, {
          enabled
        })
        
        if (response.data.code === 200) {
          fetchUsers(currentPage.value)
        } else {
          alert(response.data.message || `${enabled ? '启用' : '禁用'}用户失败，请稍后重试`)
        }
      } catch (error) {
        console.error('更新用户状态出错:', error)
        alert(`${enabled ? '启用' : '禁用'}用户失败，请稍后重试`)
      }
    }
    
    const resetPassword = async (userId) => {
      if (!confirm('确定要重置该用户的密码吗？')) {
        return
      }
      
      try {
        const response = await axios.post(`/api/admin/users/${userId}/reset-password`)
        
        if (response.data.code === 200) {
          alert(`密码已重置为: ${response.data.data}`)
        } else {
          alert(response.data.message || '重置密码失败，请稍后重试')
        }
      } catch (error) {
        console.error('重置密码出错:', error)
        alert('重置密码失败，请稍后重试')
      }
    }
    
    const getRoleName = (roleName) => {
      switch (roleName) {
        case 'ROLE_ADMIN': return '管理员'
        case 'ROLE_USER': return '普通用户'
        default: return roleName
      }
    }
    
    const formatDateTime = (timeString) => {
      if (!timeString) return '未知'
      
      const date = new Date(timeString)
      return date.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit'
      })
    }
    
    onMounted(fetchUsers)
    
    return {
      loading,
      users,
      currentPage,
      totalItems,
      totalPages,
      searchQuery,
      roleFilter,
      statusFilter,
      showEditModal,
      editingUser,
      isSaving,
      fetchUsers,
      searchUsers,
      editUser,
      saveUser,
      toggleUserStatus,
      resetPassword,
      getRoleName,
      formatDateTime
    }
  }
}
</script> 